package Test.countDownLatchDemo;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author handsomePot
 * @date 2022/1/5 22:39
 */
public class MasterWaitSon {

    public static void main(String[] args) throws InterruptedException {

        CountDownLatch countDownLatch = new CountDownLatch(8);

        ExecutorService executorService = Executors.newFixedThreadPool(10);

        for (int i = 0; i < 8; i++) {
            executorService.submit(new WorkerRunnable(i, countDownLatch));
        }


        long begin = System.currentTimeMillis();
        countDownLatch.await();
        long end = System.currentTimeMillis();
        System.out.println("一共耗时：" + (end - begin) + "ms");
    }

    public static class WorkerRunnable implements Runnable {

        private CountDownLatch latch;
        private int id;

        public WorkerRunnable(int id, CountDownLatch latch) {
            this.latch = latch;
            this.id = id;
        }

        @Override
        public void run() {
            runWork();
        }

        public void runWork() {
            System.out.println("编号:" + id + "   开始执行");
            try {
                TimeUnit.MILLISECONDS.sleep(500L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                latch.countDown();
            }
            System.out.println("=== 编号:" + id + "   执行结束");
        }
    }

}
